package com.example.demo.controller;

import com.example.demo.common.AppVariable;
import com.example.demo.common.ResultAjax;

import com.example.demo.model.UserInfo;
import com.example.demo.model.vo.UserInfoVO;
import com.example.demo.service.ArticleService;
import com.example.demo.service.UserService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 实现注册功能
     */
    @RequestMapping("/reg")
    public ResultAjax reg(UserInfo userInfo) {
        if(userInfo == null || !StringUtils.hasLength(userInfo.getUsername())
                || !StringUtils.hasLength(userInfo.getPassword())) {
            return ResultAjax.fail(-1,"非法数据");

        }else  {
            int result = userService.reg(userInfo);
            return ResultAjax.succ(result);
        }
    }

    /**
     * 实现登录
     */
    @RequestMapping("/login")
    public ResultAjax login(UserInfoVO userInfoVO, HttpServletRequest request) {//这里使用一个扩展类user接收参数
        //1，进行一个参数的检查
        if(userInfoVO == null || !StringUtils.hasLength(userInfoVO.getUsername()) ||
        !StringUtils.hasLength(userInfoVO.getPassword())) {
            return ResultAjax.fail(-1,"非法参数");
        }
        //2，将前端传过来的参数与数据库中的数据进行对比
        UserInfo userInfo = userService.getUserByName(userInfoVO);
        //3，进行用户名比对
        if(!userInfo.getUsername().equals(userInfoVO.getUsername())) {
            return ResultAjax.fail(-2,"用户名或密码错误");
        }
        //4，进行密码比对
        if(!userInfo.getPassword().equals(userInfoVO.getPassword())) {
            return ResultAjax.fail(-2,"用户名或密码错误");
        }
        //5，建立一个session链接
        HttpSession session = request.getSession();
        session.setAttribute(AppVariable.SESSION_USERINFO_KEY,userInfo);
        //6，将数据返回前端
        return ResultAjax.succ(1);
    }
    /**
     * 实现注销功能
     * 在controller层实现，不涉及dao层，service层
     */
    @RequestMapping("/loginout")
    public ResultAjax loginOut(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppVariable.SESSION_USERINFO_KEY) != null) {
            session.removeAttribute(AppVariable.SESSION_USERINFO_KEY);
        }
        return ResultAjax.succ(1);
    }
}
